package com.ship.dispatch.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.utils.bean.BeanUtils;
import com.ship.dispatch.bean.Compatibility.QueryShipAffiliatedDetailsRq;
import com.ship.dispatch.bean.Compatibility.QueryShipAffiliatedPortCollectRq;
import com.ship.dispatch.bean.Compatibility.QueryShipAffiliatedToPortRq;
import com.ship.dispatch.bean.Compatibility.QueryShipToPortRq;
import com.ship.dispatch.bean.Compatibility.vo.*;
import com.ship.dispatch.bean.DomesticVesselVoyage;
import com.ship.dispatch.bean.DomesticVesselVoyageTitle;
import com.ship.dispatch.bean.ShipVoyage;
import com.ship.dispatch.bean.SpBoatsVoyageMessage;
import com.ship.dispatch.bean.boats.QueryBoatsBaseRq;
import com.ship.dispatch.bean.boats.QueryPortSisterRq;
import com.ship.dispatch.bean.boats.QueryShipInsideInfo;
import com.ship.dispatch.bean.boats.info.*;
import com.ship.dispatch.bo.ItemStatisticsSimpleBo;
import com.ship.dispatch.mapper.BoatsVoyageMessageMapper;
import com.ship.dispatch.service.BoatsVoyageMessageService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.SpInformationService;
import com.ship.dispatch.util.DateErgodicUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>BoatsVoyageMessageServiceImpl</b>
 *
 * @description: BoatsVoyageMessageServiceImpl <br>
 * @date: 2024/4/12 16:23 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class BoatsVoyageMessageServiceImpl extends ServiceImpl<BoatsVoyageMessageMapper, SpBoatsVoyageMessage> implements BoatsVoyageMessageService {
    private static final Logger logger = LoggerFactory.getLogger(BoatsVoyageMessageServiceImpl.class);

    @Autowired
    private SpDispatchSchemeExecuteService spDispatchSchemeExecuteService;

    @Autowired
    private SpInformationService spInformationService;


    @Override
    public List<QueryBoatsVoyageMessagesInfo> queryShipExportVolumeTotal(String startDate, String endDate) {
        List<QueryBoatsVoyageMessagesInfo> resultList = new ArrayList<>();
        List<QueryBoatsVoyageMessagesInfo> queryBoatsVoyageMessagesInfos = baseMapper.queryShipExportVolumeTotal(startDate, endDate);
        if (CollectionUtil.isNotEmpty(queryBoatsVoyageMessagesInfos)) {
            if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
                Map<String, List<QueryBoatsVoyageMessagesInfo>> map = queryBoatsVoyageMessagesInfos.stream().collect(Collectors.groupingBy(QueryBoatsVoyageMessagesInfo::getTotalDate));
                List<String> dateList = DateErgodicUtil.dateErgodicUtil(startDate, endDate);
                dateList.forEach(item -> {
                    QueryBoatsVoyageMessagesInfo queryBoatsVoyageMessagesInfo = new QueryBoatsVoyageMessagesInfo();
                    queryBoatsVoyageMessagesInfo.setTotalDate(item);
                    if (CollectionUtil.isNotEmpty(map.get(item))){
                        queryBoatsVoyageMessagesInfo.setExportVolumeTotal(map.get(item).get(0).getExportVolumeTotal());
                    }
                    resultList.add(queryBoatsVoyageMessagesInfo);
                });
            }else {
                resultList.addAll(queryBoatsVoyageMessagesInfos);
            }
        }
        return resultList;
    }

    @Override
    public List<QueryBoatsVoyageMessagesInfo> shipExportVolumeTotalByCountryName(String totalDate) {
        return baseMapper.shipExportVolumeTotalByCountryName(totalDate);
    }

    @Override
    public List<QueryBoatsVoyageMessagesInfo> queryShipPortExportVolume(String startDate, String endDate) {
        return baseMapper.queryShipPortExportVolume(startDate,endDate);
    }

    @Override
    public List<QueryBoatsVoyageMessagesInfo> queryhipPortEntranceVolume(String startDate, String endDate) {
        return baseMapper.queryhipPortEntranceVolume(startDate,endDate);
    }

    @Override
    public List<QueryBoatsVoyageMessagesInfo> shipQuantityVoyage(String startDate, String endDate) {
        return baseMapper.shipQuantityVoyage(startDate,endDate);
    }

    @Override
    public Object monthlyDomesticVesselVoyage(ItemStatisticsSimpleBo bo) {
        List<ShipVoyage> shipVoyageList = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        List<DomesticVesselVoyageTitle> titleList = getTitleList();
        ShipVoyage shipVoyage = new ShipVoyage();
        shipVoyage.setTitleList(titleList);
        String startDate = DateUtil.format(bo.getStartTime(), DatePattern.NORM_DATE_FORMATTER);
        String endDate = DateUtil.format(bo.getEndTime(), DatePattern.NORM_DATE_FORMATTER);
        List<DomesticVesselVoyage> vesselVoyageList = baseMapper.monthlyDomesticVesselVoyage(startDate,endDate);
        shipVoyage.setVesselVoyageList(vesselVoyageList);
        shipVoyageList.add(shipVoyage);
        jsonObject.put("dataList", shipVoyageList);
        return jsonObject;
    }

    //top5进口贸易流向
    @Override
    public Object queryEntranceTrade(String startDateStr, String endDateStr) {
        List<SpBoatsVoyageMessage> vesselVoyageList = baseMapper.queryEntranceTrade(startDateStr,endDateStr);
        JSONObject jsonObject = new JSONObject();
        if (CollectionUtil.isNotEmpty(vesselVoyageList)){
            List<QueryEntranceTradeInfo> voyageList =new ArrayList<>();
            List<QueryEntranceTradeInfo> list = new ArrayList<>();
            Map<String, List<SpBoatsVoyageMessage>> voyageMap = vesselVoyageList.stream().collect(Collectors.groupingBy(SpBoatsVoyageMessage::getLoadCountry));
            Map<String, List<SpBoatsVoyageMessage>> dischargeCountryMap = vesselVoyageList.stream()
                    .filter(item -> StringUtils.isNotEmpty(item.getDischargeCountry()))
                    .filter(item -> StringUtils.isNotEmpty(item.getLoadCountry()))
                    .collect(Collectors.groupingBy(SpBoatsVoyageMessage::getDischargeCountry));
            dischargeCountryMap.forEach((key,value) -> {
                QueryEntranceTradeInfo tradeInfo = new QueryEntranceTradeInfo();
                tradeInfo.setCountryName(key);
                BigDecimal total = BigDecimal.ZERO;
                for (SpBoatsVoyageMessage spBoatsVoyageMessage : value) {
                    total = total.add(new BigDecimal(spBoatsVoyageMessage.getTotalCargoProspect()));
                }
                BigDecimal result = total.divide(new BigDecimal(10000));
                tradeInfo.setTrafficTotal(result.setScale(0, RoundingMode.HALF_UP));
                list.add(tradeInfo);
            });
            List<QueryEntranceTradeInfo> resultList = list.stream().sorted(Comparator.comparing(QueryEntranceTradeInfo::getTrafficTotal).reversed()).limit(5).collect(Collectors.toList());
            resultList.forEach(item -> {
                List<SpBoatsVoyageMessage> boatsVoyageMessages = dischargeCountryMap.get(item.getCountryName());
                boatsVoyageMessages.forEach(value -> {
                    QueryEntranceTradeInfo tradeInfo = new QueryEntranceTradeInfo();
                    tradeInfo.setLoadCountry(value.getLoadCountry());
                    tradeInfo.setCountryName(item.getCountryName());
                    BigDecimal result =  new BigDecimal(value.getTotalCargoProspect()).divide(new BigDecimal(10000));
                    tradeInfo.setTrafficTotal(result.setScale(0, RoundingMode.HALF_UP));
                    voyageList.add(tradeInfo);
                });
            });
            List<QueryEntranceTradeInfo> resultList1 = new ArrayList<>();
            List<QueryEntranceTradeInfo> ultimateResultList = new ArrayList();
            Map<String, Map<String, List<QueryEntranceTradeInfo>>> map = voyageList.stream().collect(Collectors.groupingBy(QueryEntranceTradeInfo::getCountryName, Collectors.groupingBy(QueryEntranceTradeInfo::getLoadCountry)));
            map.forEach((key,value) -> {
                List<QueryEntranceTradeInfo> tradeList1 = new ArrayList<>();
                value.forEach((k,v) -> {
                    QueryEntranceTradeInfo tradeInfo = new QueryEntranceTradeInfo();
                    tradeInfo.setLoadCountry(k);
                    tradeInfo.setCountryName(key);
                    BigDecimal total = BigDecimal.ZERO;
                    for (QueryEntranceTradeInfo queryEntranceTradeInfo : v) {
                        total = total.add(queryEntranceTradeInfo.getTrafficTotal());
                    }
                    tradeInfo.setTrafficTotal(total);
                    tradeList1.add(tradeInfo);
                });
                BigDecimal totalNumber = BigDecimal.ZERO;
                List<QueryEntranceTradeInfo> tradeList2 = tradeList1.stream().sorted(Comparator.comparing(QueryEntranceTradeInfo::getTrafficTotal).reversed()).limit(5).collect(Collectors.toList());
                for (QueryEntranceTradeInfo tradeInfo : tradeList2) {
                    totalNumber = totalNumber.add(tradeInfo.getTrafficTotal());
                }
                Map<String, List<QueryEntranceTradeInfo>> map1 = resultList.stream().collect(Collectors.groupingBy(QueryEntranceTradeInfo::getCountryName));
                QueryEntranceTradeInfo tradeInfo = map1.get(key).get(0);
                tradeInfo.setTrafficTotal(totalNumber);
                ultimateResultList.add(tradeInfo);
                resultList1.addAll(tradeList2);
            });

            jsonObject.put("nodes",resultList1);
            jsonObject.put("links",ultimateResultList);
        }
        return jsonObject;
    }

    @Override
    public Integer queryVoyageNumberByChina(String startDate, String endDate) {
        return baseMapper.queryShipNumberByChina(startDate,endDate);
    }

    @Override
    public Integer queryExportVolumeTotal(String startDate, String endDate) {
        return baseMapper.queryExportVolumeTotal(startDate,endDate);
    }

    @Override
    public Object queryVoyageNumber(ItemStatisticsSimpleBo bo) {
        String startTime = null;
        String endTime = null;
        if (bo.getStartTime() != null){
            startTime = DateUtil.format(bo.getStartTime(), DatePattern.NORM_DATE_FORMATTER);
            endTime = DateUtil.format(bo.getEndTime(), DatePattern.NORM_DATE_FORMATTER);
        }
//        else {
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(new Date());
//            calendar.set(Calendar.DAY_OF_MONTH, 1);
//            Calendar startDate = (Calendar) calendar.clone();
//            startTime = DateUtil.format(startDate.getTime(), DatePattern.NORM_DATE_FORMATTER);
//            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
//            Calendar endDate = (Calendar) calendar.clone();
//            endTime = DateUtil.format(endDate.getTime(), DatePattern.NORM_DATE_FORMATTER);
//        }
        List<SpBoatsVoyageMessage> vesselVoyageList = baseMapper.queryVoyageNumberByChina(startTime,endTime);
        JSONObject jsonObject = new JSONObject();
        if (CollectionUtil.isNotEmpty(vesselVoyageList)){
            List<QueryVoyageInfo> voyageList =new ArrayList<>();
            List<QueryVoyageList> list = new ArrayList<>();
            Map<String, List<SpBoatsVoyageMessage>> voyageMap = vesselVoyageList.stream().collect(Collectors.groupingBy(SpBoatsVoyageMessage::getLoadCountry));
            Map<String, List<SpBoatsVoyageMessage>> dischargeTerminalMap = vesselVoyageList.stream().collect(Collectors.groupingBy(SpBoatsVoyageMessage::getDischargeTerminal));
            voyageMap .forEach((key,value) ->{
                if (StringUtils.isNotEmpty(key)){
                    QueryVoyageInfo queryVoyageInfo = new QueryVoyageInfo();
                    queryVoyageInfo.setName(key);
                    queryVoyageInfo.setType("country");
                    BigDecimal total = BigDecimal.ZERO;
                    List<SpBoatsVoyageMessage> boatsVoyageMessages = voyageMap.get(key);
                    if (CollectionUtil.isNotEmpty(boatsVoyageMessages)){

                        Map<String,List<SpBoatsVoyageMessage>> termMap = boatsVoyageMessages.stream().collect(Collectors.groupingBy(SpBoatsVoyageMessage::getDischargeTerminal));
                        for (String s : termMap.keySet()) {
                            List<SpBoatsVoyageMessage> dataList = termMap.get(s);
                            for (SpBoatsVoyageMessage boatsVoyageMessage : dataList) {
                                total = total.add(new BigDecimal(boatsVoyageMessage.getTotalCargoProspect()));
                            }
                            QueryVoyageList queryVoyageList = new QueryVoyageList();
                            queryVoyageList.setSource(key);
                            queryVoyageList.setTarget(s);
                            queryVoyageList.setValue(dataList.size());
                            list.add(queryVoyageList);
                        }

                    }
                    queryVoyageInfo.setTrafficTotal(total.intValue());
                    voyageList.add(queryVoyageInfo);
                }
            });
            dischargeTerminalMap.forEach((key,value) -> {
                QueryVoyageInfo queryVoyageInfo1 = new QueryVoyageInfo();
                queryVoyageInfo1.setName(key);
                queryVoyageInfo1.setType("port");
                voyageList.add(queryVoyageInfo1);
            });
            jsonObject.put("nodes",voyageList);
            jsonObject.put("links",list);
        }
        return jsonObject;
    }

    @Override
    public Object queryMonthlyVoyageNumber(ItemStatisticsSimpleBo bo) {
        List<String> imoList = spDispatchSchemeExecuteService.queryImoList(bo);
        JSONObject jsonObject = new JSONObject();
        if (CollectionUtil.isNotEmpty(imoList)){
            String startTime = null;
            String endTime = null;
            if (bo.getStartTime() != null){
                startTime = DateUtil.format(bo.getStartTime(), DatePattern.NORM_DATE_FORMATTER);
                endTime = DateUtil.format(bo.getEndTime(), DatePattern.NORM_DATE_FORMATTER);
            }
//            else {
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(new Date());
//                calendar.set(Calendar.DAY_OF_MONTH, 1);
//                Calendar startDate = (Calendar) calendar.clone();
//                startTime = DateUtil.format(startDate.getTime(), DatePattern.NORM_DATE_FORMATTER);
//                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
//                Calendar endDate = (Calendar) calendar.clone();
//                endTime = DateUtil.format(endDate.getTime(), DatePattern.NORM_DATE_FORMATTER);
//            }
            List<SpBoatsVoyageMessage> vesselVoyageList = baseMapper.queryMonthlyVoyageNumber(startTime,endTime,imoList);
            if (CollectionUtil.isNotEmpty(vesselVoyageList)){
                List<QueryVoyageInfo> voyageList =new ArrayList<>();
                List<QueryVoyageList> list = new ArrayList<>();
                Map<String, List<SpBoatsVoyageMessage>> voyageMap = vesselVoyageList.stream().collect(Collectors.groupingBy(SpBoatsVoyageMessage::getLoadCountry));
                Map<String, List<SpBoatsVoyageMessage>> dischargeTerminalMap = vesselVoyageList.stream().collect(Collectors.groupingBy(SpBoatsVoyageMessage::getDischargeTerminal));
                voyageMap.forEach((key,value) ->{
                    if (StringUtils.isNotEmpty(key)){
                        QueryVoyageInfo queryVoyageInfo = new QueryVoyageInfo();
                        queryVoyageInfo.setName(key);
                        queryVoyageInfo.setType("country");
                        Integer total = 0;
                        List<SpBoatsVoyageMessage> boatsVoyageMessages = voyageMap.get(key);
                        if (CollectionUtil.isNotEmpty(boatsVoyageMessages)){
                            for (SpBoatsVoyageMessage boatsVoyageMessage : boatsVoyageMessages) {
                                total = total+Integer.parseInt(boatsVoyageMessage.getTotalCargoProspect());
                                QueryVoyageList queryVoyageList = new QueryVoyageList();
                                queryVoyageList.setSource(key);
                                queryVoyageList.setTarget(boatsVoyageMessage.getDischargeTerminal());
                                queryVoyageList.setValue(dischargeTerminalMap.get(boatsVoyageMessage.getDischargeTerminal()).size());
                                list.add(queryVoyageList);

                            }
                        }
                        queryVoyageInfo.setTrafficTotal(total);
                        voyageList.add(queryVoyageInfo);
                    }
                });
                dischargeTerminalMap.forEach((key,value) -> {
                    QueryVoyageInfo queryVoyageInfo1 = new QueryVoyageInfo();
                    queryVoyageInfo1.setName(key);
                    queryVoyageInfo1.setType("port");
                    voyageList.add(queryVoyageInfo1);
                });
                jsonObject.put("nodes",voyageList);
                jsonObject.put("links",list);
            }
        }
        return jsonObject;
    }

    @Override
    public List<QueryMonthlyCountInfo> queryMonthlyShipCount(String startDate, String endDate) {
        return baseMapper.queryMonthlyShipCount(startDate,endDate);
    }

    @Override
    public List<QueryBoatsVoyageMessagesInfo> queryDischargeCapacity(String startDate, String endDate) {
        return baseMapper.queryDischargeCapacity(startDate,endDate);
    }

    @Override
    public List<QueryBoatsVoyageMessagesInfo> shipEntranceVolumeTotal(String startDate, String endDate) {
        return baseMapper.queryDischargeCapacity(startDate,endDate);
    }

    @Override
    public List<QueryBoatsVoyageMessagesInfo> shipEntranceVolumeTotalByCountryName(String totalDate) {
        return baseMapper.shipEntranceVolumeTotalByCountryName(totalDate);
    }

    /**
     * 分页查询船舶挂靠港口列表
     * @param rq
     * @return
     */
    @Override
    public PageInfo<QueryShipToPortInfo> queryShipAffiliatedPortPage(QueryShipToPortRq rq) {
        if (StringUtils.isNotEmpty(rq.getShipName())){
            String imo = baseMapper.queryImoByShipName(rq.getShipName());
            rq.setImo(imo);
        }

        if (StringUtils.isNotEmpty(rq.getSisterStatus()) && "1".equals(rq.getSisterStatus())){
            List<QueryShipToPortInfo> shipToPortInfoList = baseMapper.queryShipAffiliatedPortPage(rq);
            List<String> list1 = shipToPortInfoList.stream().map(QueryShipToPortInfo::getImo).collect(Collectors.toList());
            List<String> imoList = list1.stream().distinct().collect(Collectors.toList());
            //查询姊妹船列表
            List<String> sisterIdList = baseMapper.queryBoatsPortSisterAll(imoList);
            List<String> list2 = sisterIdList.stream().distinct().collect(Collectors.toList());
            PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
            List<QueryShipToPortInfo> list = baseMapper.queryShipAffiliatedPortSister(list2,rq.getReceivingStation());
            list.addAll(shipToPortInfoList);
            if (CollectionUtil.isNotEmpty(list)){
                PageInfo<QueryShipToPortInfo> pageInfo = new PageInfo<>(list);
//                for (QueryShipToPortInfo queryShipToPortInfo : pageInfo.getList()) {
//                    String shipName = baseMapper.queryShipNameByImo(queryShipToPortInfo.getImo());
//                    queryShipToPortInfo.setShipName(shipName);
//                }
                return pageInfo;
            }

        }else {
            PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
            List<QueryShipToPortInfo> shipToPortList = baseMapper.queryShipAffiliatedPortPage(rq);
            PageInfo<QueryShipToPortInfo> pageInfo = new PageInfo<>(shipToPortList);
//            for (QueryShipToPortInfo queryShipToPortInfo : pageInfo.getList()) {
//                String shipName = baseMapper.queryShipNameByImo(queryShipToPortInfo.getImo());
//                queryShipToPortInfo.setShipName(shipName);
//            }
            return pageInfo;
        }

        return null;
    }

    @Override
    public List<QueryShipToPortInfo> exportShipAffiliatedPort(QueryShipToPortRq rq) {
        if (StringUtils.isNotEmpty(rq.getShipName())){
            String imo = baseMapper.queryImoByShipName(rq.getShipName());
            rq.setImo(imo);
        }
        List<QueryShipToPortInfo> shipToPortList = baseMapper.queryShipAffiliatedPortPage(rq);
        if (CollectionUtil.isNotEmpty(shipToPortList)){
            shipToPortList.forEach(item -> {
                String shipName = baseMapper.queryShipNameByImo(item.getImo());
                item.setShipName(shipName);
            });
        }
        if (StringUtils.isNotEmpty(rq.getShipName()) || StringUtils.isNotEmpty(rq.getImo())){
            //查询当前船舶所有姊妹船信息
            if (CollectionUtil.isNotEmpty(shipToPortList) && "1".equals(rq.getSisterStatus())){
                //查询姊妹船列表
                List<String> sisterIdList = baseMapper.queryBoatsPortSisterList(shipToPortList.get(0).getImo());
                List<QueryShipToPortInfo> list = baseMapper.queryShipAffiliatedPortSister(sisterIdList,rq.getReceivingStation());
                if (CollectionUtil.isNotEmpty(list)){
                    list.forEach(item -> {
                        String shipName = baseMapper.queryShipNameByImo(item.getImo());
                        item.setShipName(shipName);
                    });
                    shipToPortList.addAll(list);
                }
            }
        }
        return shipToPortList;
    }

    @Override
    public QueryShipAffiliatedDetailsInfo queryShipAffiliatedPortDetails(QueryShipAffiliatedDetailsRq rq) {
        QueryShipAffiliatedDetailsInfo info = new QueryShipAffiliatedDetailsInfo();
        List<QueryShipAffiliatedDetailsInfo> affiliatedDetailsList = baseMapper.countAffiliatedNumber(rq);
        if (CollectionUtil.isNotEmpty(affiliatedDetailsList)){
            Integer portOfCallNumberTotal = 0;
            for (QueryShipAffiliatedDetailsInfo queryShipAffiliatedDetailsInfo : affiliatedDetailsList) {
                portOfCallNumberTotal = portOfCallNumberTotal + queryShipAffiliatedDetailsInfo.getPortOfCallNumberTotal();
            }
            BeanUtils.copyProperties(affiliatedDetailsList.get(0),info);
            info.setPortOfCallNumberTotal(portOfCallNumberTotal);
            Integer berthNumber = baseMapper.countBerthNumber(rq);
            info.setPortBerthageNumber(berthNumber);
            List<String> list1 = affiliatedDetailsList.stream().map(QueryShipAffiliatedDetailsInfo::getImo).collect(Collectors.toList());
            List<String> imoList = list1.stream().distinct().collect(Collectors.toList());
            //查询姊妹船列表
            List<String> sisterIdList = baseMapper.queryBoatsPortSisterAll(imoList);
            List<QueryShipToPortInfo> list = baseMapper.queryShipAffiliatedPortSister(sisterIdList.stream().distinct().collect(Collectors.toList()),rq.getReceivingStation());
            Map<String, List<QueryShipToPortInfo>> imoMap = list.stream().collect(Collectors.groupingBy(QueryShipToPortInfo::getImo));
            info.setSisterBoatsNumber(imoMap.size());
        }
        return info;
    }

    @Override
    public PageInfo<QueryShipAffiliatedPortCollectInfo> queryShipAffiliatedPortCollect(QueryShipAffiliatedPortCollectRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        List<QueryShipAffiliatedPortCollectInfo> portCollectInfoList = baseMapper.queryShipAffiliatedPortCollect(rq);
        return new PageInfo<QueryShipAffiliatedPortCollectInfo>(portCollectInfoList);
    }

    @Override
    public List<QueryShipAffiliatedPortCollectInfo> exportShipAffiliatedPortCollect(QueryShipAffiliatedPortCollectRq rq) {
        List<QueryShipAffiliatedPortCollectInfo> portCollectInfoList = baseMapper.queryShipAffiliatedPortCollect(rq);
        return portCollectInfoList;
    }

    @Override
    public List<QueryBoatsPortSisterInfo> queryBoatsPortSisterList(QueryPortSisterRq rq) {
        List<QueryBoatsPortSisterInfo> resultList = new ArrayList<>();
        QueryBoatsBaseRq queryBoatsBaseRq = new QueryBoatsBaseRq();
        queryBoatsBaseRq.setShipName(rq.getShipName());
        List<String> boatsPortSisterList = baseMapper.queryBoatsPortSisterList(rq.getImo());
        if (CollectionUtil.isNotEmpty(boatsPortSisterList)){
            List<QueryShipToPortInfo> list = baseMapper.queryShipAffiliatedPortSister(boatsPortSisterList.stream().distinct().collect(Collectors.toList()),rq.getReceivingStation());
            List<String> imoList = list.stream().map(QueryShipToPortInfo::getImo).collect(Collectors.toList());
            List<String> queryImoList = imoList.stream().distinct().collect(Collectors.toList());
            queryBoatsBaseRq.setBoatsPortSisterList(queryImoList);
            List<QueryBoatsPortSisterInfo> boatsPortSisterInfos = spInformationService.queryBoatsSister(queryBoatsBaseRq);
            if (CollectionUtil.isNotEmpty(boatsPortSisterInfos)){
                Map<String, List<QueryBoatsPortSisterInfo>> stringListMap = boatsPortSisterInfos.stream().collect(Collectors.groupingBy(QueryBoatsPortSisterInfo::getSisterImo));
                Map<String, List<QueryShipToPortInfo>> shipToPortMap = list.stream().collect(Collectors.groupingBy(QueryShipToPortInfo::getImo));
                queryImoList.forEach(item -> {
                    QueryBoatsPortSisterInfo queryBoatsPortSisterInfo = stringListMap.get(item).get(0);
                    queryBoatsPortSisterInfo.setReceivingStation(shipToPortMap.get(item).get(0).getReceivingStation());
                    resultList.add(queryBoatsPortSisterInfo);
                });
            }
        }
        return resultList;
    }

    @Override
    public String queryShipNameByImo(String imo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("imo",imo);
        queryWrapper.eq("enable","1");
        List<SpBoatsVoyageMessage> voyageMessageList = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(voyageMessageList)){
            return voyageMessageList.get(0).getShipName();
        }
        return null;
    }

    @Override
    public List<String> queryMessage(String type) {
        if ("shipName".equals(type)){
            return baseMapper.queryMessageByShipName();
        }else if ("imo".equals(type)){
            return baseMapper.queryMessageByImo();
        }else if ("loadTerminal".equals(type)){
            return baseMapper.queryMessageByTerminal();
        }else if ("port".equals(type)){
            return baseMapper.queryPortNameList();
        }
        return null;
    }


    @Override
    public PageInfo<QueryShipAffiliatedToPortPageInfo> queryShipAffiliatedToPortPage(QueryShipAffiliatedToPortRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        List<QueryShipAffiliatedToPortPageInfo> pageList = baseMapper.queryShipAffiliatedToPortPage(rq);
        PageInfo<QueryShipAffiliatedToPortPageInfo> pageInfo = new PageInfo<>(pageList);
        return pageInfo;
    }

    @Override
    public List<QueryShipAffiliatedToPortPageInfo> exportShipAffiliatedToPort(QueryShipAffiliatedToPortRq rq) {
        List<QueryShipAffiliatedToPortPageInfo> pageList = baseMapper.queryShipAffiliatedToPortPage(rq);
        return pageList;
    }

    @Override
    public PageInfo<QueryShipToPortInfo> queryPortAffiliatedShipPage(QueryShipToPortRq rq) {
        if (StringUtils.isNotEmpty(rq.getShipName())){
            String imo = baseMapper.queryImoByShipName(rq.getShipName());
            rq.setImo(imo);
        }

        if (StringUtils.isNotEmpty(rq.getSisterStatus()) && "1".equals(rq.getSisterStatus())){
            List<QueryShipToPortInfo> shipToPortInfoList = baseMapper.queryShipAffiliatedPortPage(rq);
            List<String> list1 = shipToPortInfoList.stream().map(QueryShipToPortInfo::getImo).collect(Collectors.toList());
            List<String> imoList = list1.stream().distinct().collect(Collectors.toList());
            //查询姊妹船列表
            List<String> sisterIdList = baseMapper.queryBoatsPortSisterAll(imoList);
            PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
            List<QueryShipToPortInfo> list = baseMapper.queryShipAffiliatedPortSister(sisterIdList.stream().distinct().collect(Collectors.toList()),rq.getReceivingStation());
            list.addAll(shipToPortInfoList);
            if (CollectionUtil.isNotEmpty(list)){
                PageInfo<QueryShipToPortInfo> pageInfo = new PageInfo<>(list);
//                for (QueryShipToPortInfo queryShipToPortInfo : pageInfo.getList()) {
//                    String shipName = baseMapper.queryShipNameByImo(queryShipToPortInfo.getImo());
//                    queryShipToPortInfo.setShipName(shipName);
//                }
                return pageInfo;
            }

        }else {
            PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
            List<QueryShipToPortInfo> shipToPortList = baseMapper.queryShipAffiliatedPortPage(rq);
//            if (CollectionUtil.isNotEmpty(shipToPortList)){
//                shipToPortList.forEach(item -> {
//                    String shipName = baseMapper.queryShipNameByImo(item.getImo());
//                    item.setShipName(shipName);
//                });
//            }
            return new PageInfo<QueryShipToPortInfo>(shipToPortList);
        }







//        if (StringUtils.isNotEmpty(rq.getShipName()) || StringUtils.isNotEmpty(rq.getImo()) || StringUtils.isEmpty(rq.getReceivingStation())){
//            //查询当前船舶所有姊妹船信息
//            if (CollectionUtil.isNotEmpty(shipToPortList) && "1".equals(rq.getSisterStatus())){
//                List<String> list1 = shipToPortList.stream().map(QueryShipToPortInfo::getImo).collect(Collectors.toList());
//                List<String> imoList = list1.stream().distinct().collect(Collectors.toList());
//                //查询姊妹船列表
//                List<String> sisterIdList = baseMapper.queryBoatsPortSisterAll(imoList);
//                List<QueryShipToPortInfo> list = baseMapper.queryShipAffiliatedPortSister(sisterIdList.stream().distinct().collect(Collectors.toList()),rq.getReceivingStation());
//                if (CollectionUtil.isNotEmpty(list)){
//                    list.forEach(item -> {
//                        String shipName = baseMapper.queryShipNameByImo(item.getImo());
//                        item.setShipName(shipName);
//                    });
//                    shipToPortList.addAll(list);
//                }
//            }
//        }
        return null;
    }

    @Override
    public PortAffiliatedShipInfo queryPortAffiliatedShipByImo(QueryShipAffiliatedDetailsRq rq) {
//        PortAffiliatedShipInfo portAffiliatedShipInfo = new PortAffiliatedShipInfo();
        PortAffiliatedShipInfo portAffiliatedShipList = baseMapper.queryPortAffiliatedShipByImo(rq);
//        if (CollectionUtil.isNotEmpty(portAffiliatedShipList)){
//            BeanUtils.copyProperties(portAffiliatedShipList.get(0),portAffiliatedShipInfo);
//            Integer number = 0;
//            for (PortAffiliatedShipInfo affiliatedShipInfo : portAffiliatedShipList) {
//                number = number + affiliatedShipInfo.getPortOfCallNumberTotal();
//            }
//            portAffiliatedShipInfo.setPortOfCallNumberTotal(number);
//            portAffiliatedShipInfo.setReceivingStation(rq.getReceivingStation());
//        }
        if (null != portAffiliatedShipList){
            portAffiliatedShipList.setReceivingStation(rq.getReceivingStation());
        }
        return portAffiliatedShipList;
    }

    @Override
    public PageInfo<QueryPortAffiliatedToShipInfo> queryPortAffiliatedToShip(QueryShipAffiliatedToPortRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        if (StringUtils.isNotEmpty(rq.getShipName())){
            String imo = baseMapper.queryImoByShipName(rq.getShipName());
            rq.setImo(imo);
        }
        List<QueryPortAffiliatedToShipInfo> affiliatedToShipList = baseMapper.queryPortAffiliatedToShip(rq);
        PageInfo<QueryPortAffiliatedToShipInfo> pageInfo = new PageInfo<>(affiliatedToShipList);
        return pageInfo;
    }

    @Override
    public List<QueryPortAffiliatedToShipInfo> exportPortAffiliatedToShip(QueryShipAffiliatedToPortRq rq) {
        return baseMapper.queryPortAffiliatedToShip(rq);
    }

    @Override
    public List<QueryShipInsideInfo> queryShipCountryInside(String startDate, String endDate) {
        List<QueryShipInsideInfo> resultList = baseMapper.queryShipCountryInside(startDate,endDate);
        return resultList;
    }

    public List<DomesticVesselVoyageTitle> getTitleList(){
        List<DomesticVesselVoyageTitle> titleList = new ArrayList<>();
        DomesticVesselVoyageTitle domesticVesselVoyageTitle = new DomesticVesselVoyageTitle();
        domesticVesselVoyageTitle.setTitle("船名");
        domesticVesselVoyageTitle.setKey("shipName");
        titleList.add(domesticVesselVoyageTitle);
        DomesticVesselVoyageTitle domesticVesselVoyageTitle1 = new DomesticVesselVoyageTitle();
        domesticVesselVoyageTitle1.setTitle("发货国");
        domesticVesselVoyageTitle1.setKey("loadCountry");
        titleList.add(domesticVesselVoyageTitle1);
        DomesticVesselVoyageTitle domesticVesselVoyageTitle2 = new DomesticVesselVoyageTitle();
        domesticVesselVoyageTitle2.setTitle("收货港");
        domesticVesselVoyageTitle2.setKey("dischargePort");
        titleList.add(domesticVesselVoyageTitle2);
        DomesticVesselVoyageTitle domesticVesselVoyageTitle3 = new DomesticVesselVoyageTitle();
        domesticVesselVoyageTitle3.setTitle("到港时间");
        domesticVesselVoyageTitle3.setKey("dischargeInPortTime");
        titleList.add(domesticVesselVoyageTitle3);
        DomesticVesselVoyageTitle domesticVesselVoyageTitle4 = new DomesticVesselVoyageTitle();
        domesticVesselVoyageTitle4.setTitle("货量");
        domesticVesselVoyageTitle4.setKey("totalCargoProspect");
        titleList.add(domesticVesselVoyageTitle4);
        return titleList;
    }
}
